<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-back" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="nav-title">账号登录</text>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 主要内容 -->
    <view class="login-content">
      <!-- Logo区域 -->
      <view class="logo-section">
        <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
        <text class="app-name">欢迎登录</text>
        <text class="app-desc">请输入您的账号和密码</text>
      </view>

      <!-- 登录表单 -->
      <view class="login-form">
        <!-- 账号输入 -->
         <view class="input-wrapper">
           <view class="input-group">
          <view class="input-icon">
            <text class="iconfont icon-user">👤</text>
          </view>
          <input
            class="input-field"
            type="text"
            placeholder="请输入手机号"
            v-model="formData.phone"
            :class="{ 'input-error': errors.phone }"
          />
        </view>
        <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>


         </view>
       
        <!-- 密码输入 -->
         <view class="input-wrapper">
              <view class="input-group">
          <view class="input-icon">
            <text class="iconfont icon-lock">🔒</text>
          </view>
          <input
            class="input-field"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="formData.password"
            :class="{ 'input-error': errors.password }"
          />
          <view class="password-toggle" @click="togglePassword">
            <text class="toggle-icon">{{ showPassword ? "👁️" : "👁️‍🗨️" }}</text>
          </view>
        </view>
        <text v-if="errors.password" class="error-text">{{
          errors.password
        }}</text>

         </view>
    

     

        <!-- 登录按钮 -->
        <button
          class="login-btn"
          :class="{ 'btn-loading': isLoading }"
          @click="handleLogin"
        >
          <text v-if="isLoading" class="loading-icon">⏳</text>
          <text class="btn-text">{{ isLoading ? "登录中..." : "登录" }}</text>
        </button>

        <!-- 注册链接 -->
        <view class="register-link">
          <text class="register-text">还没有账号？</text>
          <text class="register-btn" @click="handleRegister">立即注册</text>
        </view>
        <view class="agreement-section">
          <view class="agreement-check" @click="toggleAgreement">
            <view class="checkbox" :class="{ checked: agreeTerms }">
              <text v-if="agreeTerms" class="check-icon">✓</text>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="agreement-link" @click.stop="showUserAgreement"
                >《用户协议》</text
              >
              和
              <text class="agreement-link" @click.stop="showPrivacyPolicy"
                >《隐私政策》</text
              >
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from "vue";
import request from "@/api/request.js";

// 响应式数据
const formData = reactive({
  phone: "",
  password: "",
});
const agreeTerms = ref(false);
const errors = reactive({
  phone: "",
  password: "",
});
const showPassword = ref(false);
const rememberMe = ref(false);
const isLoading = ref(false);


const toggleAgreement = () => {
  agreeTerms.value = !agreeTerms.value;
};
const hasErrors = computed(() => {
  return errors.phone || errors.password;
});

// 方法
const validateForm = () => {
  errors.phone = "";
  errors.password = "";

  if (!formData.phone.trim()) {
    errors.phone = "请输入手机号";
    return false;
  }

  if (!formData.phone.match(/^1[3456789]\d{9}$/)) {
    errors.phone = "请输入正确的手机号";
    return false;
  }

  if (!formData.password.trim()) {
    errors.password = "请输入密码";
    return false;
  }

  if (formData.password.length < 6) {
    errors.password = "密码长度不能少于6位";
    return false;
  }
  if (!agreeTerms.value) {
    uni.showToast({
      title: "请同意用户协议和隐私政策",
      icon: "none",
    });
    return false;
  }
  return true;
};

const togglePassword = () => {
  showPassword.value = !showPassword.value;
};



const handleLogin = async () => {
  if (!validateForm()) {
    return;
  }
  isLoading.value = true;

  try {
    // POST请求
    const res = await request.post("/api/auth/login", {
      phone: formData.phone,
      password: formData.password,
    });
    
    // 保存登录状态
    uni.setStorageSync("token", res.data.token);
    uni.setStorageSync("userInfo", res.data.user);
    
    // 获取当前页面栈
    const pages = getCurrentPages();
    console.log('登录成功，当前页面栈:', pages);
    
    // 延迟执行以确保状态完全保存
    setTimeout(() => {
      // 判断是否存在有效的历史记录(非登录页面)
      let hasValidHistory = false;
      
      // 检查页面栈中是否有非登录页面
      for (let i = 0; i < pages.length - 1; i++) {
        if (pages[i].route !== "/pages/login/index") {
          hasValidHistory = true;
          break;
        }
      }
      
      if (hasValidHistory) {
        // 如果有有效历史记录，返回到前一个非登录页面
        // 清除所有历史记录中的登录页面，避免多个登录页面堆积
        const currentPageIndex = pages.length - 1;
        let targetIndex = -1;
        
        // 从后向前查找最近的非登录页面
        for (let i = currentPageIndex - 1; i >= 0; i--) {
          if (pages[i].route !== "/pages/login/index") {
            targetIndex = i;
            break;
          }
        }
        
        if (targetIndex >= 0) {
          const delta = currentPageIndex - targetIndex;
          console.log(`返回${delta}层到页面: ${pages[targetIndex].route}`);
          
          // 返回到目标页面
          uni.navigateBack({
            delta: delta,
            success: () => {
              // 通知其他页面刷新数据
              uni.$emit('userLoggedIn', { userInfo: res.data.user });
              uni.$emit('update', { msg: '页面更新' });
            },
            fail: (err) => {
              console.error('返回页面失败:', err);
              // 失败时跳转到首页
              uni.switchTab({ url: "/pages/home/index" });
            }
          });
        } else {
          // 理论上不会执行到这里，但为了安全起见
          console.log('未找到有效的历史页面，跳转到首页');
          uni.switchTab({ url: "/pages/home/index" });
        }
      } else {
        // 如果没有有效历史记录，直接跳转到首页
        console.log('无有效历史记录，跳转到首页');
        uni.switchTab({ url: "/pages/home/index" });
      }
    }, 50); // 减少延迟时间，提高响应速度
  } catch (error) {
    console.error('登录失败:', error);
    uni.showToast({
      title: error.message || "登录失败，请重试",
      icon: "none",
    });
  } finally {
    isLoading.value = false;
  }
};

// 加载记住的数据
const loadRememberedData = () => {
  const rememberedUsername = uni.getStorageSync("rememberedUsername");
  const rememberMeStored = uni.getStorageSync("rememberMe");

  if (rememberMeStored && rememberedUsername) {
    formData.username = rememberedUsername;
    rememberMe.value = true;
  }
};

// 忘记密码
const handleForgotPassword = () => {
  uni.showModal({
    title: "忘记密码",
    content: "请联系管理员重置密码",
    showCancel: false,
  });
};

// 注册
const handleRegister = () => {
  uni.navigateTo({
    url: "/pages/login/register",
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
const showUserAgreement = () => {
  uni.navigateTo({
    url: "/pages/login/agreement",
  });
};

const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: "/pages/login/privacyPolicy",
  });
};
// 监听表单数据变化，实时清除错误提示
watch(
  () => formData.phone,
  (newVal) => {
    if (errors.phone) {
      // 用户开始输入时立即清除错误提示
      errors.phone = "";
    }
  },
  { immediate: false }
);

watch(
  () => formData.password,
  (newVal) => {
    if (errors.password) {
      // 用户开始输入时立即清除错误提示
      errors.password = "";
    }
  },
  { immediate: false }
);

// 生命周期
onMounted(() => {
  // 检查是否有记住的登录信息
  loadRememberedData();
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

/* 顶部导航 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  padding-top: calc(var(--status-bar-height) + 20rpx);
  position: relative;
  z-index: 10;
}

.nav-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  cursor: pointer;
}

.back-icon {
  font-size: 32rpx;
  color: #2c3e50;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #2c3e50;
}

.nav-placeholder {
  width: 60rpx;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.circle-1 {
  width: 200rpx;
  height: 200rpx;
  top: 10%;
  left: -50rpx;
  animation-delay: 0s;
}

.circle-2 {
  width: 150rpx;
  height: 150rpx;
  top: 60%;
  right: -30rpx;
  animation-delay: 2s;
}

.circle-3 {
  width: 100rpx;
  height: 100rpx;
  top: 30%;
  right: 20%;
  animation-delay: 4s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

/* 主要内容 */
.login-content {
  padding: 100rpx 60rpx 60rpx;
  position: relative;
  z-index: 1;
}

/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 80rpx;
}

.logo {
  width: 200rpx;
  height: 120rpx;
  margin-bottom: 30rpx;
}

.app-name {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #ffffff;
  margin-bottom: 20rpx;
}

.app-desc {
  display: block;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

/* 登录表单 */
.login-form {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 60rpx 40rpx;
  backdrop-filter: blur(10px);
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.1);
}
.input-wrapper {
  margin-bottom: 50rpx;
  position: relative;
}
/* 输入组 */
.input-group {
  position: relative;
  background: #f8f9fa;
  border-radius: 16rpx;
  border: 2rpx solid #e5e5e5;
  transition: all 0.3s ease;
}

.input-group:focus-within {
  border-color: #667eea;
  background: #ffffff;
  box-shadow: 0 0 0 6rpx rgba(102, 126, 234, 0.1);
}

.input-icon {
  position: absolute;
  left: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32rpx;
  color: #999;
  z-index: 2;
}

.input-field {
  width: 100%;
  height: 88rpx;
  padding: 0 120rpx 0 70rpx;
  border: none;
  background: transparent;
  font-size: 32rpx;
  color: #333;
}

.input-field::placeholder {
  color: #999;
}

.input-error {
  border-color: #ff4757 !important;
}

.password-toggle {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  cursor: pointer;
}

.toggle-icon {
  font-size: 32rpx;
  color: #999;
}

.error-text {
  color: #ff4757;
  font-size: 24rpx;
  position: absolute;
  bottom: -40rpx;
  left: 0;
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 50rpx;
}

.remember-me {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.checkbox {
  width: 32rpx;
  height: 32rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  margin-right: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.checkbox.checked {
  background: #667eea;
  border-color: #667eea;
}

.check-icon {
  color: #ffffff;
  font-size: 20rpx;
  font-weight: bold;
}

.option-text {
  font-size: 28rpx;
  color: #666;
}

.forgot-password {
  font-size: 28rpx;
  color: #667eea;
  cursor: pointer;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  transition: all 0.3s ease;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.login-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}

.btn-disabled {
  background: #ccc !important;
  box-shadow: none !important;
}

.btn-loading {
  background: #999 !important;
}

.loading-icon {
  margin-right: 16rpx;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.btn-text {
  font-size: 32rpx;
  color: #ffffff;
  font-weight: bold;
}
/* 协议部分 */
.agreement-section {
  margin-bottom: 40rpx;
}

.agreement-check {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.checkbox {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #bdc3c7;
  border-radius: 6rpx;
  margin-right: 16rpx;
  margin-top: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.checkbox.checked {
  background: #667eea;
  border-color: #667eea;
}

.check-icon {
  color: #ffffff;
  font-size: 18rpx;
  font-weight: bold;
}

.agreement-text {
  font-size: 24rpx;
  color: #7f8c8d;
  line-height: 1.5;
}

.agreement-link {
  color: #667eea;
  /* text-decoration: underline; */
}
/* 注册链接 */
.register-link {
  text-align: right;
  margin-bottom: 40rpx;
}

.register-text {
  font-size: 28rpx;
  color: #666;
}

.register-btn {
  font-size: 28rpx;
  color: #667eea;
  margin-left: 10rpx;
  cursor: pointer;
}
</style>
